﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAKS.IServices;
using SAKS.Models;
using NHibernate;
using SAKS.Services.Query;
namespace SAKS.Services
{
    public class AchievementServices : IAchievementServices
    {
        public ISession Session { get; set; }

        public IEnumerable<Award> GetAwards(Guid achiId)
        {
            var achi = Session.Get<Achievement>(achiId);
            return achi.Awards;
        }
        public void AddAward(Guid achiId, Award award)
        {
            var achi = Session.Get<Achievement>(achiId);
            achi.Awards.Add(award);
            Session.Update(achi);
        }
        public void RemoveAward(Guid achiId, Guid awardId)
        {
            var achi = Session.Get<Achievement>(achiId);
            var beremoved = from a in achi.Awards where a.Id == awardId select a;
            if(beremoved.Count() > 0)
            {
                achi.Awards.Remove(beremoved.First());
            }
            Session.Update(achi);
        }

        public object[] List(int first, int pageSize, out int? totalRecords, string key)
        {
            PagedAchiListSearch search = new PagedAchiListSearch(Session){
                First = first,
                Name = key,
                PageSize = pageSize,
                Sort = SortColumn.CreatedDateDesc
            };

            var result = search.Execute();
            totalRecords = result.TotalItems;
            var query = from a in result.PageOfResults
                    select new string[]{
                            a.Id.ToString(),
                            a.Name,
                            a.MissionOrigin,
                            a.PrimaryCompletePerson,
                            a.PrimaryCompleteOrganization,
                            a.CreatedDate.ToString("yyyy-MM-dd")
                        };
            return query.ToArray();
        }

        public void Save(Achievement achi)
        {
            Session.Save(achi);
        }

        public Achievement Get(Guid id)
        {
            var query = Session.QueryOver<Achievement>().Where(a => a.Id == id)
                .JoinQueryOver(a => a.Evaluation);
            return query.SingleOrDefault();
        }

        public void Delete(Guid id)
        {
            var o = Session.Get<Achievement>(id);
            if (o != null)
                Session.Delete(o);
        }

        public void Update(Achievement a)
        { }
    }
}
